<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="关联鱼塘" prop="fishPondId">
                <el-select v-model="ruleForm.fishPondId" filterable clearable class="w100p"
                    @change="handleChangeFishPond">
                    <el-option v-for="(item, index) in fishPondList" :key="index" :label="item.pondName"
                        :value="item.fishPondId" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择批次" prop="productionBatchId">
                <el-select v-model="ruleForm.productionBatchId" filterable clearable class="w100p">
                    <el-option v-if="ruleForm.fishPondId == item.fishPondId" v-for="(item, index) in batchList"
                        :key="index" :label="item.batchName" :value="item.batchId" />
                </el-select>
            </el-form-item>
            <el-form-item label="季节">
                <el-select v-model="ruleForm.season" filterable clearable class="w100p">
                    <el-option label="春季" value="春季" />
                    <el-option label="夏季" value="夏季" />
                    <el-option label="秋季" value="秋季" />
                    <el-option label="冬季" value="冬季" />
                </el-select>
            </el-form-item>
            <el-form-item label="作业位置">
                <el-input v-model="ruleForm.position" placeholder="请输入作业位置信息"></el-input>
            </el-form-item>
            <el-form-item label="作业天数">
                <el-input v-model="ruleForm.day" placeholder="请输入作业天数"></el-input>
            </el-form-item>
            <el-form-item label="作业次数">
                <el-input v-model="ruleForm.time" placeholder="请输入作业次数"></el-input>
            </el-form-item>
            <el-row v-if="addEditFlag == 'add'" v-for="item, index in ruleForm.materialList" :key="index">
                <el-col :span="10">
                    <el-form-item :label="index == 0 ? '饲料名称' : ''" :prop="`materialList[${index}][materialId]`"
                        :rules="rules.materialId">
                        <el-select class="w100p" filterable clearable v-model="item.materialId" placeholder="请选择">
                            <el-option v-for="(m, i) of materialList" :key="i" :label="m.name" :value="m.materialId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item class="noLabel" :prop="`materialList[${index}][num]`" :rules="rules.num">
                        <el-input type="number" v-model="item.num" placeholder="请输入数量"
                            @change="handleChangeNum(item, index)">
                            <template slot="append">{{ item.materialId ? materialObj[item.materialId].unit : ""
                                }}</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item class="noLabel" :prop="`materialList[${index}][convertNum]`"
                        :rules="rules.convertNum">
                        <el-input type="number" v-model="item.convertNum" placeholder="请输入数量"
                            @change="handleChangeconvertNum(item, index)">
                            <template slot="append">{{ item.materialId ? materialObj[item.materialId].aUnit :
        "" }}</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <i class="icon el-icon-circle-plus-outline" @click.stop="addMaterial()"></i>
                    <i v-show="index" class="icon el-icon-remove-outline" @click.stop="delMaterial(index)"></i>
                </el-col>
            </el-row>
            <template v-if="addEditFlag == 'edit'">
                <el-row :gutter="15">
                    <el-col :span="8">
                        <el-form-item label="饲料名称" prop="materialId">
                            <el-select class="w100p" filterable clearable v-model="ruleForm.materialId"
                                placeholder="请选择">
                                <el-option v-for="(m, i) of materialList" :key="i" :label="m.name"
                                    :value="m.materialId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8"><el-form-item class="noLabel" prop="num">
                            <el-input type="number" v-model="ruleForm.num" placeholder="请输入数量"
                                @change="handleChangeNum()">
                                <template slot="append">{{ ruleForm.materialId ? materialObj[ruleForm.materialId].unit :
        ""
                                    }}</template>
                            </el-input>
                        </el-form-item></el-col>
                    <el-col :span="8"><el-form-item class="noLabel" prop="convertNum">
                            <el-input type="number" v-model="ruleForm.convertNum" placeholder="请输入数量"
                                @change="handleChangeconvertNum()">
                                <template slot="append">{{ ruleForm.materialId ? materialObj[ruleForm.materialId].aUnit
        : "" }}</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </template>
            <el-form-item label="作业人" prop="staffId">
                <el-select v-model="ruleForm.staffId" filterable clearable class="w100p" @change="handleChangeStaff">
                    <el-option v-for="item, index in staffList" :key="index" :label="item.staffName"
                        :value="item.staffId" />
                </el-select>
            </el-form-item>
            <el-form-item label="作业日期" prop="workDateTime">
                <el-date-picker v-model="ruleForm.workDateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                    placeholder="选择日期" :picker-options="pickerOptions" class="w100p">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel(false)">取 消</el-button>
            <SaveDraftBox ref="saveDraft" v-if="addEditFlag == 'add' && dialogVisible" :formData="ruleForm" @pushData="pushData">
            </SaveDraftBox>
            <el-button type="primary" v-show="!ruleForm.inputPondId" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import store from "@/store";
import feedingOperation from '@/api/production-management/feeding-operation.js';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        fishPondList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        fishVarietyList: {
            type: Array,
            default: () => {
                return []
            }
        },
        specificationList: {
            type: Array,
            default: () => {
                return []
            }
        },
        staffList: {
            type: Array,
            default: () => {
                return []
            }
        },
        materialList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let checkNum = (rule, value, callback) => {
            if (value) {
                if (Number(value) > 0 && Number(value) <= 99999 && Number(value) % 1 == 0) {
                    callback();
                } else if (Number(value) > 99999) {
                    callback(new Error('请输入小于100000的整数'));
                } else {
                    callback(new Error('请输入大于0的整数'));
                }
            } else {
                callback(new Error('请输入数值'));
            }
        };
        let num = (rule, value, callback) => {
            if (value) {
                if (Number(value) > 0 && Number(value) <= 99999) {
                    callback();
                } else if (Number(value) > 99999) {
                    callback(new Error('请输入小于100000的数'));
                } else {
                    callback(new Error('请输入大于0的数'));
                }
            } else {
                callback(new Error('请输入数值'));
            }
        };
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() >= Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: num, trigger: 'change' }
                ],
                time: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                day: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                convertNum: [
                    { required: true, validator: num, trigger: 'change' }
                ],
                workDateTime: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
                fishPondId: [
                    { required: true, message: '请选择鱼塘', trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择操作人', trigger: 'change' }
                ],
                materialId: [
                    { required: true, message: '请选择物料', trigger: 'change' }
                ],
            }
        }
    },
    computed: {
        materialObj() {
            console.log(store.state.basicData.material)
            return store.state.basicData.material;
        }
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = feedingOperation.add
                this.addEditName = '添加';
                this.getInitRulFormData();
                if (this.ruleForm.materialList && Array.isArray(this.ruleForm.materialList)) {
                    this.$set(this.ruleForm.materialList, 0, {
                        convertNum: null, num: null, materialId: null
                    })
                } else {
                    this.$set(this.ruleForm, 'materialList', [{
                        convertNum: null, num: null, materialId: null
                    }])
                }
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.addEditApi = feedingOperation.edit
                this.addEditName = '编辑';
                this.$set(this.ruleForm, 'convertNum', 0);
                this.handleChangeNum(this.ruleForm)
            }
        },
        pushData(data) {
            this.ruleForm = { ...data };
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
            })
        },
        //转换投喂量
        handleChangeNum(row) {
            if (this.addEditFlag == 'edit') {
                row = this.ruleForm;
                this.$set(this.ruleForm, 'convertNum', 0)
            }
            if (!row.num) {
                return
            } else {
                let num = row.num = Number(row.num)
                row.convertNum = num / this.materialObj[row.materialId].ratioNum
            }
        },
        //转换投喂量
        handleChangeconvertNum(row) {
            if (this.addEditFlag == 'edit') {
                row = this.ruleForm
            }
            if (!row.convertNum) {
                return
            } else {
                let convertNum = Number(row.convertNum)
                row.num = convertNum * this.materialObj[row.materialId].ratioNum
            }
        },
        //添加饲料
        addMaterial() {
            let length = this.ruleForm.materialList?.length || 0
            if (length) {
                this.$set(this.ruleForm.materialList, length, {
                    convertNum: null, num: null, materialId: null
                })
            }
        },
        //删除饲料
        delMaterial(index) {
            let list = this.ruleForm.materialList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'materialList', list)
        },
        //初始化一些表单数据
        getInitRulFormData() {
            let id = sessionStorage.getItem('staffId') || null;
            let params = {
                staffId: id == 'null' ? '' : Number(id),
                workDateTime: this.$formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss'),
                time: 2,
                day: 1
            }
            this.$set(this, 'ruleForm', params);
        },
        //选择鱼塘时提示用户是否存在该关联批次
        handleChangeFishPond(id) {
            let rut = this.batchList.find(item => item.fishPondId == id);
            let batchId = rut?.batchId
            this.$set(this.ruleForm, 'productionBatchId', batchId || '');
            !rut && this.$message.warning('该鱼塘暂无批次!');
        },
        //选择品种时提示用户是否存在该品种规格
        handleChangeFishVariety(id) {
            let rut = this.specificationList.find(item => item.fishVarietyId == id);
            let materialId = rut?.materialId
            this.$set(this.ruleForm, 'materialId', materialId || '');
            !rut && this.$message.warning('该鱼种暂未配置规格!');
        },
        //获取称重人姓名
        handleChangeStaff(id) {
            let rut = this.staffList.find(item => item.staffId == id);
            let staffName = rut?.staffName
            this.$set(this.ruleForm, 'staffName', staffName || '');
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        let msg = res.success ? '操作成功' : '操作失败'
                        this.$message[res.success ? 'success' : 'warning'](res.message || msg)
                        res.success && this.cancel();
                        res.success && this.addEditFlag == 'add' && this.$refs.saveDraft.delByKey();
                    }).catch(err => {
                        this.$message.error(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel(falg) {
            this.resetForm()
            this.$emit("closeDialog", falg)
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
::v-deep .noLabel {
    .el-form-item__content {
        margin: 0 !important;
    }
}

.icon {
    font-size: 24px;
    line-height: 30px;
    margin-left: 15px;
}
</style>